<template>
  <div>
    <nav-bar :title="title" :isShow="false"></nav-bar>

    <!-- <van-cell icon="question-o" :title="question.name" /> -->
    <van-notice-bar color="#1989fa" background="#fff" left-icon="bar-chart-o">
      <!-- <template #right-icon>
        <van-icon name="share-o" @click="onShare" />
      </template> -->
      {{ question.name }}
    </van-notice-bar>
    <!-- 图文 -->
    <van-checkbox-group
      v-if="question.category == 0"
      v-model="result"
      @change="onChange"
      :max="question.max_num"
    >
      <div
        class="box van-hairline--top"
        v-for="item in question.choices"
        :key="item.id"
      >
        <van-image
          width="90%"
          height="14rem"
          fit="contain"
          :src="item.images.length > 0 ? item.images[0].image: '-'"
        />
        <van-checkbox :name="item" icon-size="24px">{{
          item.name
        }}</van-checkbox>
      </div>
      <van-divider></van-divider>
    </van-checkbox-group>
    <!-- 文字 -->
    <van-checkbox-group
      v-if="question.category == 1"
      v-model="result"
      @change="onChange"
      :max="question.max_num"
    >
      <van-cell-group>
        <van-cell
          v-for="(item, index) in question.choices"
          clickable
          :key="item.id"
          :title="item.name"
          @click="toggle(index)"
        >
          <template #right-icon>
            <van-checkbox :name="item" ref="checkboxes" />
          </template>
        </van-cell>
      </van-cell-group>
    </van-checkbox-group>

    <van-row type="flex" justify="center" gutter="40">
      <van-col span="8">
        <van-button
          size="small"
          round
          block
          type="info"
          @click="handleVote"
          :disabled="result.length == 0"
        >
          投 票
        </van-button>
      </van-col>
      <van-col span="8"
        ><van-button size="small" round block type="primary" @click="goResult"
          >查看结果</van-button
        ></van-col
      >
    </van-row>
    <!-- <div style="margin: 32px">
        
    </div> -->
  </div>
</template>

<script>
import NavBar from "@/components/NavBar";
import { get_jsapi_sign } from "@/api/utils";
import { getQuestionById, updateWxChoices } from "@/api/polls";

export default {
  name: "Question",

  props: ["question_id"],

  components: {
    NavBar,
  },

  data() {
    return {
      title: this.$route.meta.title,
      question: {
        id: null,
        name: "",
        desc: "",
        begin_date: null,
        end_date: null,
        category: 0,
        choices: [],
      },
      result: [],
      radio: null,
    };
  },

  created() {
    this.getJsApiSign();
    this.getQuestion();
  },

  methods: {
    getJsApiSign() {
      const url = location.href.split("#")[0];
      get_jsapi_sign(url)
        .then((res) => {
          const sign = res.data;
          this.$wx.config({
            debug: false,
            appId: sign.appId,
            timestamp: sign.timestamp,
            nonceStr: sign.nonceStr,
            signature: sign.signature,
            jsApiList: [
              "updateAppMessageShareData",
              // "openAddress",
              // "openLocation",
              // "getLocation",
            ],
          });
          setTimeout(() => {
            this.onShare();
          }, 1000);
        })
        .catch((error) => {
          console.log(error.message);
        });
    },

    getQuestion() {
      getQuestionById(this.question_id)
        .then((res) => {
          this.question = res.data;
          this.title = this.question.name;
        })
        .catch((error) => {
          this.$notify({ type: "danger", message: "读取数据失败" + error });
        });
    },

    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },

    onChange() {
      console.log(this.result);
      // if (this.question.category == 1) {
      //   this.result = [];
      //   this.result.push(this.radio);
      // }
    },

    onShare() {
      this.$wx.ready(() => {
        this.$wx.updateAppMessageShareData({
          title: this.question.name, // 分享标题
          desc: this.question.desc, // 分享描述
          link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
          imgUrl: "http://hsh.xzls.vip/media/logohsh.png", // 分享图标
          success: function () {
            // 设置成功
            console.log("successs.....");
          },
        });
      });
    },

    handleVote() {
      if (this.result.length == 0) {
        this.$toast("请选择后在提交");
        return;
      }
      const data = {
        id: this.question.id,
        openid: localStorage.getItem("openid"),
        choices: this.result,
      };

      updateWxChoices(data)
        .then((res) => {
          console.log(res);
          this.$toast("投票成功");
          this.$router.push({
            name: "QuestionResult",
            params: { question_id: this.question.id },
          });
        })
        .catch((err) => {
          console.log(err.response);
          if (err.response) {
            this.$toast(err.response.data.message);
            this.result = [];
          } else {
            this.$toast("投票失败");
          }
        });
    },

    goResult() {
      this.$router.push({
        name: "QuestionResult",
        params: { question_id: this.question.id },
      });
    },
  },
};
</script>

<style  scoped>
.van-checkbox-group {
  padding: 0 10px;
}
/* .van-cell::after{
  border-bottom: 0px;
} */
.van-row {
  margin: 32px;
}
.box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}
.van-image {
  padding: 20px;
}
.van-checkbox{
  margin-top:10px;
}
</style>